<?php

namespace app\modules\admin\models;

use app\modules\common\logic\BaseLogic;
use Yii;

/**
 * This is the model class for table "cms_post".
 *
 * @property int $id 自增主键
 * @property string $post_id 文档id
 * @property int $category_id 所属栏目
 * @property int $model_id 所属模型
 * @property string $title 文档标题
 * @property string $keywords 文档关键词
 * @property string $description 文档描述
 * @property string $main_image 文档主图
 * @property string $post_tag 文档标签，(,隔开)
 * @property int $click 点击数
 * @property string $author 作者
 * @property int $is_publish 是否发布(0未发布,10已发布)
 * @property string $is_recommed 是否推荐(0为推荐,10已推荐)
 * @property int $deleted 是否删除(0未删除，1已删除)
 * @property string $created 创建时间
 * @property string $modified 修改时间
 */
class CmsPost extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cms_post';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['post_id'], 'required'],
            [['category_id', 'model_id', 'click', 'is_publish', 'deleted'], 'integer'],
            [['created', 'modified'], 'safe'],
            [['post_id'], 'string', 'max' => 20],
            [['title', 'keywords', 'post_tag', 'is_recommed'], 'string', 'max' => 100],
            [['description'], 'string', 'max' => 200],
            [['main_image', 'author'], 'string', 'max' => 50],
            [['post_id'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', '自增主键'),
            'post_id' => Yii::t('app', '文档id'),
            'category_id' => Yii::t('app', '所属栏目'),
            'model_id' => Yii::t('app', '所属模型'),
            'title' => Yii::t('app', '文档标题'),
            'keywords' => Yii::t('app', '文档关键词'),
            'description' => Yii::t('app', '文档描述'),
            'main_image' => Yii::t('app', '文档主图'),
            'post_tag' => Yii::t('app', '文档标签，(,隔开)'),
            'click' => Yii::t('app', '点击数'),
            'author' => Yii::t('app', '作者'),
            'is_publish' => Yii::t('app', '是否发布(0未发布,10已发布)'),
            'is_recommed' => Yii::t('app', '是否推荐(0为推荐,10已推荐)'),
            'deleted' => Yii::t('app', '是否删除(0未删除，1已删除)'),
            'created' => Yii::t('app', '创建时间'),
            'modified' => Yii::t('app', '修改时间'),
        ];
    }


    /**
     * 获取下一篇文章
     * @param $id
     * @param $cateid
     * @param string $field
     * @return mixed
     */
    public function getNext($id, $field = '*')
    {
        $post_result = $this->getRecordInfoById($id);
        $result = $this->orm()
            ->andWhere(['category_id' => $post_result['category_id']])
            ->andWhere(['deleted' => 0])
            ->andWhere(['>', 'id', $post_result['id']])
            ->orderBy('id desc')
            ->asArray()
            ->one();
        return $result;
    }

    /**
     * 获取上一篇文章
     * @param $id
     * @param $cateid
     * @param string $field
     * @return mixed
     */
    public function getPre($id, $field = '*')
    {
        $post_result = $this->getRecordInfoById($id);
        $result = $this->orm()
            ->andWhere(['category_id' => $post_result['category_id']])
            ->andWhere(['deleted' => 0])
            ->andWhere(['<', 'id', $post_result['id']])
            ->orderBy('id asc')
            ->asArray()
            ->one();
        return $result;
    }


    /**
     * 获取单条记录
     * @access public
     * @author furong
     * @param $id
     * @param string $field
     * @return array|bool
     * @since 2017年7月28日 09:40:34
     * @abstract
     */
    public function getModelRecordInfoById($id, $field = '*')
    {
        $orm = $this->orm()->andWhere(['id' => $id]);
        $cms_post_result = $this->getRecordInfo($orm);
        if (!$cms_post_result) {
            return false;
        }
        $result = $this->getModelRecordInfoByPostId($cms_post_result['post_id'], $field);
        return $result;
    }

    /**
     * 获取单条记录
     * @access public
     * @author furong
     * @param $id
     * @param string $field
     * @return array|bool
     * @since 2017年7月28日 09:40:34
     * @abstract
     */
    public function getModelRecordInfoByPostId($post_id, $field = '*')
    {
        $orm = $this->orm()->andWhere(['post_id' => $post_id]);
        $cms_post_result = $this->getRecordInfo($orm);
        if (!$cms_post_result) {
            return false;
        }
        $logic = new BaseLogic();
        $model_defined = $logic->getModelDefined($cms_post_result['model_id']);
        $cms_post_extend_attribute_select_arr[] = 'post_id';
        $cms_post_extend_text_select_arr[] = 'post_id';
        foreach ($model_defined as $value) {
            if ($value['belong_to_table'] == 'cms_post_extend_attribute') {
                $cms_post_extend_attribute_select_arr[] = "max( CASE field WHEN '{$value['field_value']}' THEN `value` ELSE '' END ) AS {$value['field_value']}";
            }
            if ($value['belong_to_table'] == 'cms_post_extend_text') {
                $cms_post_extend_text_select_arr[] = "max( CASE field WHEN '{$value['field_value']}' THEN `value` ELSE '' END ) AS {$value['field_value']}";
            }
        }

        #拼接字段
        if ($field != '*') {
            $fields = explode(',', $field);
            $select_expr = [];
            foreach ($fields as $val) {
                foreach ($model_defined as $value) {
                    if ($val == $value['field_value']) {
                        $select_expr[] = $value['belong_to_table'] . '.' . $val;
                    }
                }
            }
            $field = implode(',', $select_expr);
        }

        #cms_post_extend_attribute
        {
            $cms_post_extend_attribute_raw_join = "(SELECT " . implode(',', $cms_post_extend_attribute_select_arr) . " FROM cms_post_extend_attribute  GROUP BY post_id ) as cms_post_extend_attribute";
        }
        #cms_post_extend_text
        {
            $cms_post_extend_text_raw_join = "(SELECT  " . implode(',', $cms_post_extend_text_select_arr) . " FROM cms_post_extend_text  GROUP BY post_id ) as cms_post_extend_text";
        }

        $orm = $this->orm()->leftJoin($cms_post_extend_attribute_raw_join, 'cms_post.post_id  = cms_post_extend_attribute.post_id')
            ->leftJoin($cms_post_extend_text_raw_join, 'cms_post.post_id = cms_post_extend_text.post_id')
            ->andWhere(['cms_post.post_id' => $post_id])
            ->andWhere(['cms_post.deleted' => 0]);
        $result = $orm->select($field)->asArray()->one();
        return $result;
    }


    /**
     * 获取记录列表
     * @access public
     * @author furong
     * @param $orm
     * @param string $offset
     * @param string $limit
     * @param bool $for_count
     * @param string $field
     * @return void
     * @since 2017年7月6日 17:14:49
     * @abstract
     */
    public function getModelRecordList($model_id, $orm, $offset = '', $limit = '', $for_count = false, $sort_field = 'created', $sort = 'desc', $field = '*')
    {
        $orm = $this->getOrm($orm)->andWhere(['cms_post.model_id' => $model_id])->andWhere(['cms_post.deleted' => 0]);
        #查询数据
        if ($for_count) {
            $result = $orm->count();
        } else {
            $logic = new BaseLogic();
            $model_defined = $logic->getModelDefined($model_id);
            #拼接查询字段
            $select_arr = [];
            if ($field == '*') {
                foreach ($model_defined as $value) {
                    $select_arr[] = '`' . $value['belong_to_table'] . '`.`' . $value['field_value'] . '`';
                }
            } else {
                $fields = explode(',', $field);
                foreach ($fields as $val) {
                    foreach ($model_defined as $value) {
                        if ($val == $value['field_value']) {
                            $select_arr[] = '`' . $value['belong_to_table'] . '`.`' . $val . '`';
                        }
                    }
                }
            }
            $select_expr = implode(',', array_unique($select_arr));

            #组装sql
            $cms_post_extend_attribute_select[] = 'post_id';
            $cms_post_extend_text_select[] = 'post_id';
            foreach ($model_defined as $value) {
                if ($value['belong_to_table'] == 'cms_post_extend_attribute') {
                    $cms_post_extend_attribute_select[] = "max( CASE field WHEN '{$value['field_value']}' THEN `value` ELSE '' END ) AS `{$value['field_value']}`";
                }
                if ($value['belong_to_table'] == 'cms_post_extend_text') {
                    $cms_post_extend_text_select[] = "max( CASE field WHEN '{$value['field_value']}' THEN `value` ELSE '' END ) AS `{$value['field_value']}`";
                }
            }
            #cms_post_extend_attribute
            {
                $cms_post_extend_attribute_select = implode(',', array_unique($cms_post_extend_attribute_select));
                $cms_post_extend_attribute_raw_join = "(SELECT {$cms_post_extend_attribute_select} FROM cms_post_extend_attribute  GROUP BY post_id ) as cms_post_extend_attribute";
            }
            #cms_post_extend_text
            {
                $cms_post_extend_text_select = implode(',', array_unique($cms_post_extend_text_select));
                $cms_post_extend_text_raw_join = "(SELECT {$cms_post_extend_text_select} FROM cms_post_extend_text  GROUP BY post_id ) as cms_post_extend_text";
            }
            $orm = $orm->leftJoin($cms_post_extend_attribute_raw_join, 'cms_post.post_id = cms_post_extend_attribute.post_id')
                ->leftJoin($cms_post_extend_text_raw_join, 'cms_post.post_id = cms_post_extend_text.post_id');
            $orm = $orm->select($select_expr);
            if ($offset) {
                $orm = $orm->offset($offset);
            }
            if ($limit) {
                $orm = $orm->limit($limit);
            }
            if ($sort == 'desc') {
                $orm = $orm->orderBy($sort_field . ' desc');
            } else {
                $orm = $orm->orderBy($sort_field . ' asc');
            }
            $result = $orm->asArray()->all();
        }
        return $result;
    }


    public function addModelRecord($request_data)
    {
        $request_data = hooks()->apply_filters('publish_post', $request_data);
        #获取模型定义
        $baseLogic = new BaseLogic();
        $model_defined = $baseLogic->getModelDefined($request_data['model_id']);
        $cms_post_data = [];
        $cms_post_extend_attribute_data = [];
        $cms_post_extend_text_data = [];
        foreach ($model_defined as $value) {
            if ($value['belong_to_table'] == 'cms_post') {
                if (isset($request_data[$value['field_value']])) {
                    $cms_post_data[$value['field_value']] = $request_data[$value['field_value']];
                }
            } elseif ($value['belong_to_table'] == 'cms_post_extend_attribute') {
                if (isset($request_data[$value['field_value']]) && !empty($request_data[$value['field_value']])) {
                    $cms_post_extend_attribute_data[] = [
                        'post_id' => $request_data['post_id'],
                        'field' => $value['field_value'],
                        'value' => $request_data[$value['field_value']],
                    ];
                }
            } elseif ($value['belong_to_table'] == 'cms_post_extend_text') {
                if (isset($request_data[$value['field_value']]) && !empty($request_data[$value['field_value']])) {
                    $cms_post_extend_text_data[] = [
                        'post_id' => $request_data['post_id'],
                        'field' => $value['field_value'],
                        'value' => $request_data[$value['field_value']],
                    ];
                }
            }
        }
        try {
            $transaction = \Yii::$app->db->beginTransaction();
            $result = $this->addRecord($cms_post_data);
            if (!$result) {
                throw new \Exception('文档主记录添加失败');
            }
            if ($cms_post_extend_attribute_data) {
                $cmsPostExtendAttributeModel = new CmsPostExtendAttribute();
                foreach ($cms_post_extend_attribute_data as $value) {
                    $result = $cmsPostExtendAttributeModel->addRecord($value);
                    if (!$result) {
                        throw new \Exception('文档扩展属性添加失败');
                    }
                }
            }
            if ($cms_post_extend_text_data) {
                $cmsPostExtendTextModel = new CmsPostExtendText();
                foreach ($cms_post_extend_text_data as $value) {
                    $result = $cmsPostExtendTextModel->addRecord($value);
                    if (!$result) {
                        throw new \Exception('文档扩展富文本添加失败');
                    }
                }
            }
            $transaction->commit();
            $return = true;
        } catch (\Exception $ex) {
            $transaction->rollBack();
            $this->setMessage($ex->getMessage());
            $return = false;
        }
        return $return;
    }

    /**
     * 删除文档记录
     * @access public
     * @author furong
     * @param $id
     * @return bool
     * @since 2017年7月28日 09:46:43
     * @abstract
     */
    public function deleteModelRecord($id)
    {
        $post_result = $this->getRecordInfoById($id);
        if (!$post_result) {
            $this->setMessage('文档不存在');
            return false;
        }
        try {
            $transaction = \Yii::$app->db->beginTransaction();
            #删除主记录
            $result = $this->deleteRecordById($id);
            if (!$result) {
                throw new \Exception('删除文档主记录失败');
            }
            #删除扩展记录
            $cmsPostExtendAttributeModel = new CmsPostExtendAttribute();
            $orm = $cmsPostExtendAttributeModel->orm()->andWhere(['post_id' => $post_result['post_id']]);
            $list = $cmsPostExtendAttributeModel->getAllRecord($orm);
            foreach ($list as $value) {
                $result = $cmsPostExtendAttributeModel->deleteRecordById($value['id']);
                if (!$result) {
                    throw new \Exception('删除文档扩展属性失败');
                }
            }
            $cmsPostExtendTextModel = new CmsPostExtendText();
            $orm = $cmsPostExtendTextModel->orm()->andWhere(['post_id' => $post_result['post_id']]);
            $list = $cmsPostExtendTextModel->getAllRecord($orm);
            foreach ($list as $value) {
                $result = $cmsPostExtendTextModel->deleteRecordById($value['id']);
                if (!$result) {
                    throw new \Exception('删除文档扩展富文本失败');
                }
            }
            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->setMessage($e->getMessage());
            return false;
        }
    }

}
